<template>
  <!-- 战败客户明细 -->
  <div>
    <TopFilter
      :list="topFilterList"
      :cols="3"
      @filterChange="changeHandle"
      @onCollapse="collapseHandle"
    ></TopFilter>
    <FilterTable
      ref="table"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'records'"
      :isSelectColumn="false"
      :isColumnFilter="false"
      :onColumnsChange="columns => this.columns = columns"
    ></FilterTable>
  </div>
</template>

<script>
import {
  queryFailReportDetail
 } from '@/api/report/retail/CauseOfDefeat';
import { getOrgTeam, getUserByOrgId } from '@/api/report/retail/clueFunnelAnalysis';
import { dictionary } from '@/utils/dictMixin';
import Chart1 from '@/charts/preSale/chart1';
import { authority } from '@/utils/authMixin';
import { integration, integrations, GetPercent, computedAll, getTextByJs } from '@/utils/index';
import { ObjectAssign, sortRule } from '@/components/DataMerge';
import { formatDates } from '@/utils/validate';
import moment from 'moment';
export default {
  name: 'PerformanceReport',
  mixins: [dictionary, authority],
  components: {
    Chart1
  },
  data() {
    return {
      topFilterList: this.createTopFilters(),
      fetchParams: {
        dateType: 'day',
        startDate: moment().format("YYYY-MM-DD"),
        endDate: moment().format("YYYY-MM-DD")
      },
      quarterTime: [],
      visible: false,
      conf: { add: '新增', edit: '编辑', show: '显示' },
      dataSource: [],
      fetchApi: queryFailReportDetail,
      columns: this.createTableColumns(),
    };
  },
  methods: {
    createTopFilters() {
      return [
        {
          type: 'SELECT',
          label: '日期维度',
          fieldName: 'dateType',
          placeholder: '请选择',
          initialValue: 'day',
          itemList: [
            { value: 'day', text: '日' },
            { value: 'week', text: '周' },
            { value: 'month', text: '月' },
            { value: 'quarter', text: '季' },
            { value: 'year', text: '年' },
            { value: 'date', text: '期间' }
          ],
          change: val => {
            this.changeTemplateType(val);
          }
        },
        {
          type: 'DATE',
          label: '日期',
          fieldName: 'datetime',
          placeholder: '',
          dateType: 'exactdate',
          initialValue: moment().format("YYYY-MM-DD"),
          change: (val, fieldName) => {
            // console.log(val,fieldName)
            this.quarterTime = val;
          }
        },
        {
          type: 'SELECT',
          label: '销售小组',
          fieldName: 'orgId',
          placeholder: '请选择...',
          itemList: [],
          change: val => {
            // console.log(val,fieldName)
            this.getUserByOrgId(val);
          }
        },
        {
          type: 'MULTIPLE_SELECT',
          label: '销售顾问',
          fieldName: 'consultants',
          placeholder: '请选择...',
          itemList: []
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '客户编号',
          dataIndex: 'potentialCustomerNo'
        },
        {
          title: '客户名称',
          dataIndex: 'customerName'
        },
        {
          title: '意向车型',
          dataIndex: 'intentName'
        },
        {
          title: '联系电话',
          dataIndex: 'mobilePhone'
        },
        {
          title: '初始接洽时间',
          dataIndex: 'planActionDate',
          sorter: true,
          render: props => {
            return <span>{ formatDates(props.row.planActionDate)}</span>;
          }
        },
        {
          title: '申请战败日期',
          dataIndex: 'createdAt',
          sorter: true,
          render: props => {
            return <span>{ formatDates(props.row.createdAt)}</span>;
          }
        },
        {
          title: '战败时级别',
          dataIndex: 'originalLevel',
          sorter: true,
          // filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1519'),
          render: props => {
            return <span>{this.createDictText(props.row.originalLevel, '1519')}</span>
          }
        },
        {
          title: '战败竞品车型',
          dataIndex: 'failBrand',
          render: props => {
            return <span>{ props.row.failBrand }{ props.row.failSeries }</span>;
          }
        },
        {
          title: '战败原因',
          dataIndex: 'basedataName'
        },
        {
          title: '确认日期',
          dataIndex: 'reviewDate',
          sorter: true,
          render: props => {
            return <span>{ formatDates(props.row.reviewDate)}</span>;
          }
        },
      ];
    },

    async getOrgTeam() {
      const res = await getOrgTeam();
      if (res.resultCode === 200) {
        this.topFilterList.find(item => item.fieldName === 'orgId').itemList = res.data.map(x => ({ value: x.orgId, text: x.orgName }));
      }
    },
    async getUserByOrgId(val) {
      const res = await getUserByOrgId({ orgId: val });
      if (res.resultCode === 200) {
        this.topFilterList.find(item => item.fieldName === 'consultants').itemList = res.data.map(x => ({ value: x.userId, text: x.userName }));
        this.topFilterList.find(item => item.fieldName === 'consultants').initialValue = '';
      }
    },
    changeHandle(val) {
      if (val.datetime) {
        switch (val.dateType) {
          case 'day':
            val.startDate = val.datetime;
            val.endDate = val.datetime;
            break;
          case 'week':
            var weekOfday = moment(val.datetime, 'YYYY-MM-DD').format('E'); //计算指定日期是这周第几天
            var last_monday = moment(val.datetime).subtract(weekOfday-1, 'days').format('YYYY-MM-DD');//周一日期
            var last_sunday = moment(val.datetime).add(7-weekOfday, 'days').format('YYYY-MM-DD');//周日日期
            // console.log(last_monday,last_sunday)
            val.startDate = last_monday;
            val.endDate = last_sunday;
            break;
          case 'month':
            var start_monthday = moment(val.datetime)
              .startOf('month')
              .format('YYYY-MM-DD'); //月初日期
            var last_monthday = moment(val.datetime)
              .endOf('month')
              .format('YYYY-MM-DD'); //月末日期
            // console.log(start_monthday,last_monthday)
            val.startDate = start_monthday;
            val.endDate = last_monthday;
            break;
          case 'quarter':
            val.startDate = this.quarterTime[0].split(' ')[0];
            val.endDate = this.quarterTime[1].split(' ')[0];
            // console.log(val.startDate,val.endDate)
            break;
          case 'year':
            var start_yearday = moment(val.datetime)
              .startOf('year')
              .format('YYYY-MM-DD'); //年初日期
            var last_yearday = moment(val.datetime)
              .endOf('year')
              .format('YYYY-MM-DD'); //年末日期
            // console.log(start_yearday,last_yearday)
            val.startDate = start_yearday;
            val.endDate = last_yearday;
            break;
          case 'date':
            val.startDate = val.datetime[0] ? val.datetime[0]:undefined;
            val.endDate = val.datetime[1] ? val.datetime[1]:undefined;
            break;
          default:
            break;
        }
      }
      if (val.consultants.length > 0) {
        val.consultant = getTextByJs(val.consultants);
      }
      this.fetchParams = Object.assign({}, val);
    },
    collapseHandle() {
      // this.$nextTick(() => {
      //   this.BaseTable.EXECUTE_RESET_HEIGHT();
      // });
    },
    closeHandler(val, type) {
      this.visible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    // 修改日期组件
    changeTemplateType(val) {
      switch (val) {
        case 'day':
          this.topFilterList.find(item => item.fieldName === 'datetime').type = 'DATE';
          this.topFilterList.find(item => item.fieldName === 'datetime').dateType = 'exactdate';
          this.topFilterList.find(item => item.fieldName === 'datetime').initialValue = '';
          break;
        case 'week':
          this.topFilterList.find(item => item.fieldName === 'datetime').type = 'DATE';
          this.topFilterList.find(item => item.fieldName === 'datetime').dateType = 'week';
          this.topFilterList.find(item => item.fieldName==='datetime').firstDayOfWeek = 1;
          this.topFilterList.find(item => item.fieldName === 'datetime').initialValue = '';
          break;
        case 'month':
          this.topFilterList.find(item => item.fieldName === 'datetime').type = 'DATE';
          this.topFilterList.find(item => item.fieldName === 'datetime').dateType = 'month';
          this.topFilterList.find(item => item.fieldName === 'datetime').initialValue = '';
          break;
        case 'quarter':
          this.topFilterList.find(item => item.fieldName === 'datetime').type = 'DATE';
          this.topFilterList.find(item => item.fieldName === 'datetime').dateType = 'quarter';
          this.topFilterList.find(item => item.fieldName === 'datetime').initialValue = '';
          break;
        case 'year':
          this.topFilterList.find(item => item.fieldName === 'datetime').type = 'DATE';
          this.topFilterList.find(item => item.fieldName === 'datetime').dateType = 'year';
          this.topFilterList.find(item => item.fieldName === 'datetime').initialValue = '';
          break;
        case 'date':
          this.topFilterList.find(item => item.fieldName === 'datetime').type = 'RANGE_DATE';
          this.topFilterList.find(item => item.fieldName === 'datetime').dateType = 'exactdaterange';
          this.topFilterList.find(item => item.fieldName === 'datetime').initialValue = '';
          break;
        default:
          this.topFilterList.find(item => item.fieldName === 'datetime').type = 'DATE';
          this.topFilterList.find(item => item.fieldName === 'datetime').dateType = 'exactdate';
          this.topFilterList.find(item => item.fieldName === 'datetime').initialValue = '';
          break;
      }
    }
  },
  mounted() {
    // this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  created() {
    this.getOrgTeam();
  }
};
</script>

<style lang="less" scoped>
</style>
